package com.md.config.client;

import com.md.base.BaseClient;
import com.md.config.bean.SpringContextConfig;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.client.RestTemplate;

/**
 * @author 刘骄阳
 * 2024-06-07 1:23
 */
@Configuration
@AutoConfigureAfter({
  SpringContextConfig.class,
  RetryConfiguration.class,
  ClientBefore.class,
})
@Data
public class RetryClientConfig {

  @Bean
  public BaseClient client(final RetryConfiguration retryConfiguration,
                           final RestTemplate restTemplate,
                           @Autowired(required = false) final ClientBefore clientBefore) {
    return new BaseClient(getInstance(retryConfiguration), restTemplate, clientBefore);
  }


  private RetryTemplate getInstance(final RetryConfiguration retryConfiguration) {
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    // 睡眠时间
    backOffPolicy.setInitialInterval(retryConfiguration.getRetryInterval());
    // 每次睡眠时间增加倍率
    backOffPolicy.setMultiplier(retryConfiguration.getMagnification());
    // 最大等待时间
    backOffPolicy.setMaxInterval(retryConfiguration.getMaxInterval());

    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(retryConfiguration.getMaxRetrySize(),
      retryConfiguration.getRetryAbleExceptions()));
    retryTemplate.setBackOffPolicy(backOffPolicy);
    return retryTemplate;
  }

}
